using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using BlazorSodDbManager.Models;

namespace BlazorSodDbManager.Services
{
    public class ConnectionManager
    {
        private readonly string _connectionFilePath;
        private List<DatabaseConnection> _connections;

        public ConnectionManager()
        {
            _connectionFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "connections.json");
            _connections = new List<DatabaseConnection>();
            LoadConnections();
        }

        public List<DatabaseConnection> GetConnections()
        {
            return _connections;
        }

        public DatabaseConnection GetConnection(int id)
        {
            return _connections.FirstOrDefault(c => c.Id == id);
        }

        public async Task<bool> TestConnectionAsync(DatabaseConnection connection)
        {
            var databaseService = new DatabaseService();
            return await databaseService.TestConnectionAsync(connection);
        }

        public async Task<DatabaseConnection> AddConnectionAsync(DatabaseConnection connection)
        {
            if (connection.Id == 0)
            {
                connection.Id = _connections.Count > 0 ? _connections.Max(c => c.Id) + 1 : 1;
            }

            // Test connection before adding
            if (await TestConnectionAsync(connection))
            {
                _connections.Add(connection);
                SaveConnections();
                return connection;
            }

            throw new Exception("Failed to connect to the database. Please check your connection details.");
        }

        public void UpdateConnection(DatabaseConnection connection)
        {
            var existingConnection = _connections.FirstOrDefault(c => c.Id == connection.Id);
            if (existingConnection != null)
            {
                var index = _connections.IndexOf(existingConnection);
                _connections[index] = connection;
                SaveConnections();
            }
        }

        public void DeleteConnection(int id)
        {
            var connection = _connections.FirstOrDefault(c => c.Id == id);
            if (connection != null)
            {
                _connections.Remove(connection);
                SaveConnections();
            }
        }

        private void LoadConnections()
        {
            if (File.Exists(_connectionFilePath))
            {
                try
                {
                    var json = File.ReadAllText(_connectionFilePath);
                    _connections = JsonSerializer.Deserialize<List<DatabaseConnection>>(json) ?? new List<DatabaseConnection>();
                }
                catch
                {
                    _connections = new List<DatabaseConnection>();
                }
            }
        }

        private void SaveConnections()
        {
            try
            {
                var json = JsonSerializer.Serialize(_connections, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_connectionFilePath, json);
            }
            catch
            {
                // Log error
            }
        }
    }
} 